import { Select, Form, Input, Modal, message } from 'antd';
import { useEffect, useState } from 'react';
import axios from 'axios';


const EditUser = (props) => {
  const [form] = Form.useForm();
  const { Option } = Select;

  const [roleList, setRoleList] = useState([])
  const [regionList, setRegionList] = useState([])
  const [status, setStatus] = useState([])
  useEffect(() => {
    axios.get(`http://192.168.2.3:3000/users/${props.id}`)
      .then(res => {
        console.log("user", res.data);
        form.setFieldsValue({
          "username": res.data.username,
          "password": res.data.password,
          "sex": res.data.sex,
          "roleId": res.data.roleId,
          "region": res.data.region,
          "id": res.data.id,

        });
        setStatus(res.data.status);
      });

    return () => { }
  }, []);

  useEffect(() => {
    axios.get("http://192.168.2.3:3000/roles")
      .then(res => {
        const newList = res.data.map(({ id, roleName }) => ({ label: roleName, value: id }));
        setRoleList(newList)
      })
    return () => { }
  }, []);


  useEffect(() => {
    axios.get("http://192.168.2.3:3000/regions")
      .then(res => {
        const newList = res.data.map(({ value, title }) => ({ label: title, value: value }));
        setRegionList(newList)
      })
    return () => { }
  }, []);

  const onSubmit = (values) => {
    props.setEditOpen(false);
    props.setLoading(true)
    onCreateAndGet(values)

  };



  async function onCreateAndGet(values) {
    values.status = status;
    console.log('Received values of form: ', values);
    //同步保存数据然后更新列表
    await axios.put(`http://192.168.2.3:3000/users/${props.id}`, values)
      .then(
        response => {
          console.log(response)
          if (response.status === 200) {
            message.success('保存成功');

            //异步获取新的角色数据
          } else {
            message.error('保存失败');
          }
        })
      .catch(error => {
        message.error('保存失败');
      });

    const get = await axios.get("http://192.168.2.3:3000/users?_expand=role");
    const getRes = get.data;
    console.log("getRes", getRes);
    props.setList(getRes);
    props.setLoading(false);
  };




  return (
    <Modal
      destroyOnClose={true}
      open={true}
      title="编辑用户"
      okText="确定"
      cancelText="取消"
      onCancel={() => {
        props.setEditOpen(false);;
      }}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            onSubmit(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        preserve={false}
        form={form}
        layout="vertical"

      >
        <Form.Item
          name="username"
          label="用户姓名"
          rules={[
            {
              required: true,
              message: '请输入用户姓名！',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            {
              required: true,
              message: '请输入用户密码！',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="sex"
          label="性别"
          rules={[
            {
              required: true,
              message: '请输入用户性别！',
            },
          ]}>
          <Select >
            <Option value="male">男</Option>
            <Option value="female">女</Option>
            <Option value="unknown">保密</Option>
          </Select>

        </Form.Item>

        <Form.Item
          name="roleId"
          label="角色"
          rules={[
            {
              required: true,
              message: '请选择用户角色！',
            },
          ]}>

          <Select options={roleList} />
        </Form.Item>


        <Form.Item
          name="region"
          label="区域"
          rules={[
            {
              required: true,
              message: '请选择用户区域！',
            },
          ]}
        >
          <Select options={regionList} />
        </Form.Item>

      </Form>
    </Modal>
  );
}



export default EditUser;